package com.key.service.impl;

import com.github.pagehelper.PageHelper;
import com.key.common.R;
import com.key.common.dto.BorrowDTO;
import com.key.common.vo.AssetListVO;
import com.key.common.vo.AssetsTVO;
import com.key.entity.*;
import com.key.mapper.*;
import com.key.service.BorrowAssetsService;
import com.key.utils.ExcelExportHelper;
import com.key.utils.OddNumbersUtils;
import com.key.utils.TranException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tc
 * @create 2023-02-20 10:10
 */
@Service
public class BorrowAssetsServiceImpl implements BorrowAssetsService {

    @Autowired
    BorrowAssetsMapper borrowAssetsMapper;
    @Autowired
    AssetsMapper assetsMapper;
    @Autowired
    ApplyMapper applyMapper;
    @Autowired
    ApprovalMapper approvalMapper;

    @Autowired
    IndexMapper indexMapper;

    @Autowired
    IndexAssetsMapper indexAssetsMapper;

    @Override
    public R creatBorrowed(List<Long> assetsCodes, BorrowAssets borrowAssets) {
        R r=new R();
        String borrowNumber= OddNumbersUtils.creatON("JY");
        Assets assets=new Assets();
        assets.setAssetsState(3);
        for (long i:assetsCodes) {
            borrowAssetsMapper.insertBorrowAndAssets(borrowNumber,i);
            assets.setAssetsId(i);
            assetsMapper.updateAssets(assets);
        }
        borrowAssets.setState("待审批");
        borrowAssets.setApproveProgress("发起");
        borrowAssets.setBorrowNumber(borrowNumber);
        borrowAssets.setBorrowDate(new Timestamp(System.currentTimeMillis()));
        //获取当前用户名
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        String s = String.valueOf(subject.getPrincipal());
        if(s==null||s==""){
            s="张三";
        }

        borrowAssets.setBorrower(s);
        int result=borrowAssetsMapper.insertBorrow(borrowAssets);

        Apply apply=new Apply();
        apply.setApplyNumber(borrowNumber);
        apply.setAssetNum(assetsCodes.size());
        apply.setApprover("待完善（该位置creatReceipt）");
        apply.setApplyDate(borrowAssets.getBorrowDate());
        apply.setStats("审批中");
        apply.setApplyType("资产借用");
        applyMapper.insertApply(apply);

        //领用申请审批单添加
        SysUser sysUser= indexMapper.selectUserInfoByUserName(s);
        Company company = indexAssetsMapper.selectAssetsInCompany(sysUser.getUserId());
        Department department = indexAssetsMapper.selectDeptInfoByEpmId(sysUser.getUserId());
        Approval approval = new Approval();
        approval.setState("未审批");
        approval.setApprovalNo(borrowNumber);
        approval.setApplicationType("借用");
        approval.setApplicationTime(OddNumbersUtils.getDay());
        approval.setApplicationPerson(s);
        approval.setApplicationCompany(company.getCompanyName());
        approval.setApplicationDepartment(department.getDepartmentName());

        approvalMapper.insertApproval(approval);


        if(result!=0){
            r.setCode(200);
            r.setMsg("生成单据成功！借用申请已发送");
        }else {
            r.setCode(500);
            r.setMsg("系统错误");
        }
        return r;
    }

    @Override
    public R deleteBorrowAssets(String BorrowNumbers) {
        R r=new R();
        try {
            int i= borrowAssetsMapper.deleteBorrowAssetsByBorrowNumbers(BorrowNumbers);
            int j=borrowAssetsMapper.updateBorrowAndAssets(BorrowNumbers);
            if(i!=0&&j!=0){
                r.setCode(200);
                r.setMsg("删除成功");
            }else {
                r.setCode(300);
                r.setMsg("删除失败");
            }
        }catch (Exception e){
            throw new TranException("事务错误");
        }
        return r;
    }

    @Override
    public R editBorrowAssets(BorrowDTO borrowDTO) {
        R r=new R();
        int i=borrowAssetsMapper.updateBorrowAssets(borrowDTO);
        if(i!=0){
            r.setCode(200);
            r.setMsg("修改成功！");
        }else {
            r.setCode(300);
            r.setMsg("修改失败！");
        }
        return r;
    }

    @Override
    public R findBorrowAssets(BorrowDTO borrowDTO) {
        int currentPage=borrowDTO.getCurrentPage();
        int pageSize=borrowDTO.getPageSize();
        R r=new R();

        //未分页查询，用于count获取
        List<BorrowAssets> receiptAssetsList2= borrowAssetsMapper.selectBorrow(borrowDTO);

        PageHelper.startPage(currentPage,pageSize);
        List<BorrowAssets> receiptAssetsList= borrowAssetsMapper.selectBorrow(borrowDTO);

        if(receiptAssetsList!=null){
            r.setCode(200);
            r.setMsg("success");
            r.setCount(receiptAssetsList2.size());
            r.setData(receiptAssetsList);
        }else {
            r.setCode(400);
            r.setMsg("查询失败！");
        }
        return r;
    }

    @Override
    public List<BorrowAssets> findCanReturnBorrowAssets() {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        String s = String.valueOf(subject.getPrincipal());
        List<BorrowAssets> resultList=borrowAssetsMapper.selectCanReturnBorrowAssets(s);
        return resultList;

    }

    @Override
    public List<Assets> findAssetsByBorrowAssets(BorrowAssets borrowAssets) {
        List<Assets> resultList=borrowAssetsMapper.selectAssetsByBorrowAssetsNumber(borrowAssets.getBorrowNumber());
        return resultList;
    }

    @Override
    public List<AssetsTVO> findAssetsTVOByBorrowAssets(BorrowAssets borrowAssets) {
        List<AssetsTVO> resultList=borrowAssetsMapper.selectAssetsTVOByBorrowAssetsNumber(borrowAssets.getBorrowNumber());
        return resultList;
    }

    @Override
    public HSSFWorkbook getWorkBook() {
        String[] header = {"主键ID", "办理状态", "借用单号", "借用人", "借用后使用公司", "借用后使用部门", "借用后存放地", "借用日期", "预计归还时间",
                "实际归还时间", "处理人", "审批进度", "签收状态", "借用备注"};
        String[] properties = {"borrowId", "state", "borrowNumber", "borrower", "borrowCompany", "borrowDepartment", "borrowerStoragePoint",
                "borrowDate", "estimatedReturnTime", "actualReturnTime", "handlers", "approveProgress", "sign","borrowRemarks"};

        List<BorrowAssets> borrowAssetsList=borrowAssetsMapper.selectBorrow(new BorrowDTO());

        List list = new ArrayList();
        for (BorrowAssets borrowAssets : borrowAssetsList) {
            list.add(borrowAssets);
        }

        ExcelExportHelper excelHelper = new ExcelExportHelper();
        HSSFWorkbook workbook = excelHelper.exportExcel(header, properties, list, "借用申请单表");
        return workbook;
    }
}
